package com.yuyou.fn.activity.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.yuyou.fn.activity.constant.InventoryTypeEnum;
import com.yuyou.fn.activity.entity.Activity;
import com.yuyou.fn.activity.entity.ActivityInventorySetting;
import com.yuyou.fn.activity.service.IActivityInventorySettingService;
import com.yuyou.fn.activity.service.IActivityRegSituationService;
import com.yuyou.fn.activity.service.IActivityService;
import com.yuyou.fn.activity.vo.*;
import com.yuyou.fn.common.util.*;
import com.yuyou.fn.educational.entity.Campus;
import com.yuyou.fn.educational.service.ICampusService;
import com.yuyou.fn.platform.entity.AreaTeam;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.platform.service.IAreaTeamService;
import com.yuyou.fn.report.service.IMergeStudentRegDetailService;
import com.yuyou.fn.report.vo.CampusPeriodsStudentNumVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;

import com.yuyou.fn.activity.mapper.ActivityCampusInventoryMapper;
import com.yuyou.fn.activity.entity.ActivityCampusInventory;
import com.yuyou.fn.activity.service.IActivityCampusInventoryService;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.awt.geom.Area;
import java.util.*;

/**
 *
 * ActivityCampusInventory 表数据服务层接口实现类
 *
 */
@Service
public class ActivityCampusInventoryServiceImpl extends SuperServiceImpl<ActivityCampusInventoryMapper, ActivityCampusInventory,Long> implements IActivityCampusInventoryService {

    @Resource
    private IActivityService activityService;

    @Resource
    private IAreaTeamService areaTeamService;

    @Resource
    private ICampusService campusService;
    
    @Resource
    private IActivityRegSituationService activityRegSituationService;

    @Resource
    private IActivityInventorySettingService activityInventorySettingService;

    @Resource
    private IMergeStudentRegDetailService mergeStudentRegDetailService;

    @Override
    public void saveActivityCampusInventory(ActivityInventorySetting activityInventorySetting, List<Long> campusIds) {
        if (campusIds.isEmpty()){
            return;
        }
        List<ActivityCampusInventory> activityCampusInventoryList=new ArrayList<>(campusIds.size());
        for (Long campusId:campusIds){
            ActivityCampusInventory activityCampusInventory=new ActivityCampusInventory();
            activityCampusInventory.setCampusId(campusId);
            activityCampusInventory.setActivityInventorySettingId(activityInventorySetting.getActivityInventorySettingId());
            activityCampusInventory.setMaterialName(activityInventorySetting.getMaterialName());
            activityCampusInventory.setType(activityInventorySetting.getType());
            activityCampusInventory.setUnitPrice(activityInventorySetting.getUnitPrice());
            activityCampusInventory.setUseMsg(activityInventorySetting.getUseMsg());
            activityCampusInventory.setActivityId(activityInventorySetting.getActivityId());
            activityCampusInventory.setPeriodIds(activityInventorySetting.getPeriodIds());
            activityCampusInventory.setFirstUseAdvance(0);
            activityCampusInventory.setAddUseAdvance(0);
            activityCampusInventory.setOtherUseAdvance(0);
            activityCampusInventory.setPeriodNames(activityInventorySetting.getPeriodNames());
            activityCampusInventory.setShelvesStatus(activityInventorySetting.getShelvesStatus());
            activityCampusInventory.setCreateTime(TimeUtils.now());
            activityCampusInventory.setUpdateTime(TimeUtils.now());
            activityCampusInventoryList.add(activityCampusInventory);
        }
        this.insertBatch(activityCampusInventoryList);
    }

    @Override
    public void updateByActivityInventorySettingId(long activityInventorySettingId, ActivityInventorySetting activityInventorySetting) {
        Example<ActivityCampusInventory> example=ActivityCampusInventory.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("activityInventorySettingId",activityInventorySettingId);
        ActivityCampusInventory activityCampusInventory=new ActivityCampusInventory();
        activityCampusInventory.setActivityInventorySettingId(activityInventorySetting.getActivityInventorySettingId());
        activityCampusInventory.setMaterialName(activityInventorySetting.getMaterialName());
        activityCampusInventory.setType(activityInventorySetting.getType());
        activityCampusInventory.setUnitPrice(activityInventorySetting.getUnitPrice());
        activityCampusInventory.setUseMsg(activityInventorySetting.getUseMsg());
        activityCampusInventory.setActivityId(activityInventorySetting.getActivityId());
        activityCampusInventory.setPeriodIds(activityInventorySetting.getPeriodIds());
        activityCampusInventory.setShelvesStatus(activityInventorySetting.getShelvesStatus());
        this.updateSelectiveByExample(activityCampusInventory,example);
    }

    @Override
    public Page<ActivityCampusInventoryDetailVo> findInventoryDetailBySettingId(DataPermission dataPermission, ActivityCampusInventoryQueryVo activityCampusInventoryQueryVo, int pageNo, int pageSize) {
        if (activityCampusInventoryQueryVo.getEndDate()!=null){
            activityCampusInventoryQueryVo.setEndDate(TimeUtils.changeOneDateLastTime(activityCampusInventoryQueryVo.getEndDate()));
        }
        Map<Long,AreaTeam> areaTeamMap=areaTeamService.findAreaTeamMap();
        Example<ActivityCampusInventory> example=ActivityCampusInventory.createExample();
        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillCondition(criteria,activityCampusInventoryQueryVo);
        criteria.andIn("campusId",dataPermission.getCampusIds());
        example.orderBy("createTime").desc();
        Page<ActivityCampusInventory> activityCampusInventoryPage = this.findPageByExample(example, pageNo, pageSize);
        Page<ActivityCampusInventoryDetailVo> activityCampusInventoryDetailVoPage= Utils.newPage(activityCampusInventoryPage);

        List<ActivityCampusInventory> activityCampusInventoryList=activityCampusInventoryPage.getRecords();
        if (activityCampusInventoryList!=null){
            List<Long> activityIds = Utils.removeDuplicate(BeanUtils.toList(activityCampusInventoryList, "activityId"));
            List<Long> activityInventorySettingIds =  Utils.removeDuplicate(BeanUtils.toList(activityCampusInventoryList, "activityInventorySettingId"));
            List<ActivityInventorySetting> activityInventorySettingList=activityInventorySettingService.findByIds(activityInventorySettingIds);
            List<Long> periodIds=new ArrayList<>();
            for (ActivityInventorySetting activityInventorySetting:activityInventorySettingList){
                if (StringUtils.isNotEmpty(activityInventorySetting.getPeriodIds())){
                    periodIds.addAll(Utils.toLongIds(activityInventorySetting.getPeriodIds()));
                }
            }
            periodIds=Utils.removeDuplicate(periodIds);
            Map<Long, ActivityInventorySetting> activityInventorySettingMap = BeanUtils.toMap(activityInventorySettingList, "activityInventorySettingId");
            Map<String, ActivityQuantityVo>  activityQuantityMap=new HashMap<>();//key:activityId_campusId;
            Map<Long,Activity> activityMap=new HashMap<>();
            Map<String,CampusPeriodsStudentNumVo> campusPeriodsStudentNumVoMap=new HashMap<>();//key:periodId_campusId;
            if (!Utils.isEmpty(activityIds)){
                activityMap=BeanUtils.toMap(activityService.findByIds(activityIds,"activityId","activityName"),"activityId");
                List<ActivityQuantityVo> activityQuantityVoList = activityRegSituationService.findActivityQuantityByActivityIds(activityIds);
                for (ActivityQuantityVo activityQuantityVo:activityQuantityVoList){
                    String key=activityQuantityVo.getActivityId()+"_"+activityQuantityVo.getCampusId();
                    if (!activityQuantityMap.containsKey(key)){
                        activityQuantityMap.put(key,activityQuantityVo);
                    }
                }
            }else {
                List<CampusPeriodsStudentNumVo> campusPeriodsStudentNumVoList = mergeStudentRegDetailService.findCampusPeriodsRegNum(periodIds);
                for (CampusPeriodsStudentNumVo campusPeriodsStudentNumVo:campusPeriodsStudentNumVoList){
                    String key=campusPeriodsStudentNumVo.getPeriodId()+"_"+campusPeriodsStudentNumVo.getCampusId();
                    if (!campusPeriodsStudentNumVoMap.containsKey(key)){
                        campusPeriodsStudentNumVoMap.put(key,campusPeriodsStudentNumVo);
                    }

                }
            }


            List<Long> campusIds=BeanUtils.toList(activityCampusInventoryList,"campusId");
            List<Campus> campusList=campusService.findByIds(campusIds);
            Map<Long, Campus> campusMap = BeanUtils.toMap(campusList, "campusId");
            List<ActivityCampusInventoryDetailVo> activityCampusInventoryDetailVoList=new ArrayList<>(activityCampusInventoryList.size());
            for (ActivityCampusInventory activityCampusInventory:activityCampusInventoryList){

                ActivityInventorySetting activityInventorySetting=activityInventorySettingMap.get(activityCampusInventory.getActivityInventorySettingId());
                AreaTeam areaTeam=areaTeamMap.get(activityInventorySetting.getAreaTeamId());

                ActivityCampusInventoryDetailVo activityCampusInventoryDetailVo = new ActivityCampusInventoryDetailVo();
                BeanUtils.copyProperties(activityCampusInventoryDetailVo, activityCampusInventory);
                activityCampusInventoryDetailVo.setAreaTeamName(areaTeam.getName());
                activityCampusInventoryDetailVo.setCampusName(campusMap.get(activityCampusInventory.getCampusId()).getCampusName());
                activityCampusInventoryDetailVo.setAllocatedQuantity(0);
                if (activityCampusInventory.getActivityId() != null) {
                    Activity activity=activityMap.get(activityCampusInventory.getActivityId());
                    activityCampusInventoryDetailVo.setActivityName(activity.getActivityName());
                    ActivityQuantityVo activityQuantity=activityQuantityMap.get(activityCampusInventory.getActivityId()+"_"+activityCampusInventory.getCampusId());
                    activityCampusInventoryDetailVo.setAllocatedQuantity(activityQuantity==null?0:activityQuantity.getAllocatedQuantity());
                }else {
                    Set<Long> studentIds=new HashSet<>();
                    if (StringUtils.isNotEmpty(activityInventorySetting.getPeriodIds())){
                        Long campusId=activityCampusInventory.getCampusId();

                        for (Long periodId:Utils.toLongIds(activityInventorySetting.getPeriodIds())){
                            String key=periodId+"_"+campusId;
                            CampusPeriodsStudentNumVo campusPeriodsStudentNumVo=campusPeriodsStudentNumVoMap.get(key);
                            if (campusPeriodsStudentNumVo!=null && StringUtils.isNotEmpty(campusPeriodsStudentNumVo.getStudentIds())){
                                studentIds.addAll(Utils.toLongIds(campusPeriodsStudentNumVo.getStudentIds()));
                            }
                        }
                    }

                    activityCampusInventoryDetailVo.setAllocatedQuantity(studentIds.size());
                }
                activityCampusInventoryDetailVoList.add(activityCampusInventoryDetailVo);
            }

            activityCampusInventoryDetailVoPage.setRecords(activityCampusInventoryDetailVoList);
        }

        return activityCampusInventoryDetailVoPage;
    }

    @Override
    public void updateByIdAndUpdateVo(long activityCampusInventoryId, ActivityCampusInventoryUpdateVo activityCampusInventoryUpdateVo) {
        ActivityCampusInventory activityCampusInventory=new ActivityCampusInventory();
        activityCampusInventory.setActivityCampusInventoryId(activityCampusInventoryId);
        BeanUtils.copyProperties(activityCampusInventory,activityCampusInventoryUpdateVo);
        activityCampusInventory.setUpdateTime(TimeUtils.now());
        this.updateSelectiveById(activityCampusInventory);
    }

    @Override
    public SXSSFWorkbook exporteActivityCampusInventory(DataPermission dataPermission,ActivityCampusInventoryQueryVo activityCampusInventoryQueryVo) {
        Page<ActivityCampusInventoryDetailVo> inventoryDetailVoPage = this.findInventoryDetailBySettingId(dataPermission,  activityCampusInventoryQueryVo,1,10000);
        return activityCampusInventory2excel(inventoryDetailVoPage.getRecords());
    }

    public static SXSSFWorkbook activityCampusInventory2excel(List<ActivityCampusInventoryDetailVo> activityCampusInventoryDetailVoList) {

        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("校区库存");
        SXSSFRow firstRow = sheet.createRow(0);
        String[] titles = new String[]{ "区域","类别","关联活动","关联期数","校区","物料名称","大概单价","用途","初次预数","加预数","特殊尺寸","物料使用反馈","额外使用量","预约量","余数","上架状态"};

        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }

        int rowNum = 1;

        if (activityCampusInventoryDetailVoList!=null){
            for (ActivityCampusInventoryDetailVo activityCampusInventoryDetailVo : activityCampusInventoryDetailVoList) {
                int cellNum = 0;

                SXSSFRow row = sheet.createRow(rowNum++);

                SXSSFCell cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityCampusInventoryDetailVo.getAreaTeamName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(EnumUtils.getName(InventoryTypeEnum.values(),activityCampusInventoryDetailVo.getType()));


                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityCampusInventoryDetailVo.getActivityName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityCampusInventoryDetailVo.getPeriodNames()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityCampusInventoryDetailVo.getCampusName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityCampusInventoryDetailVo.getMaterialName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(activityCampusInventoryDetailVo.getUnitPrice()==null?"0":activityCampusInventoryDetailVo.getUnitPrice().toString());


                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityCampusInventoryDetailVo.getUseMsg()));

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(activityCampusInventoryDetailVo.getFirstUseAdvance());

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(activityCampusInventoryDetailVo.getAddUseAdvance());

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityCampusInventoryDetailVo.getSpecialSize()));



                cell = row.createCell(cellNum++);
                cell.setCellValue(activityCampusInventoryDetailVo.getUseFeedback());


                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(activityCampusInventoryDetailVo.getOtherUseAdvance());


                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(activityCampusInventoryDetailVo.getAllocatedQuantity());



                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(activityCampusInventoryDetailVo.getFirstUseAdvance()+activityCampusInventoryDetailVo.getAddUseAdvance()-activityCampusInventoryDetailVo.getAllocatedQuantity()-activityCampusInventoryDetailVo.getOtherUseAdvance());


                cell = row.createCell(cellNum++);
                cell.setCellValue(activityCampusInventoryDetailVo.getShelvesStatus()==0?"下架":"上架");

            }
        }
        return excel;
    }

}